<template>
  <div class="container">
    <div class="app-container">
      <el-card class="never">
        <p>{{ $route.query.id ? '试题修改' : '试题录入' }}</p>
        <el-form
          :model="questionsNew"
          :rules="questionsNewRules"
          ref="questionsNewRuleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="学科" prop="subjectID">
            <el-select
              v-model="questionsNew.subjectID"
              placeholder="请选择"
              class="textWidth"
              @change="changeItem"
            >
              <el-option
                v-for="item in Subjectslist"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目录" prop="catalogID">
            <el-select
              v-model="questionsNew.catalogID"
              placeholder="请选择"
              class="textWidth"
            >
              <el-option
                v-for="item in directoryslist"
                :label="item.directoryName"
                :value="item.id"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="企业" prop="enterpriseID">
            <el-select
              v-model="questionsNew.enterpriseID"
              placeholder="请选择"
              class="textWidth"
            >
              <!-- :value="item.shortName" -->
              <el-option
                v-for="item in companyslist"
                :label="item.company"
                :value="item.id"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="城市" prop="province">
            <el-row style="width: 400px">
              <el-col :span="11" style="margin-right: 16px">
                <el-select
                  v-model="questionsNew.province"
                  placeholder="请选择"
                  @change="citychange"
                >
                  <el-option
                    v-for="(item, index) in provinces"
                    :key="index"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-col>
              <el-col :span="12">
                <el-select v-model="questionsNew.city" placeholder="请选择">
                  <el-option
                    v-for="(item, index) in citys"
                    :key="index"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="方向" prop="direction">
            <el-select
              v-model="questionsNew.direction"
              placeholder="请选择"
              class="textWidth"
            >
              <el-option
                v-for="(item, index) in direction"
                :value="item"
                :key="index"
                :label="item"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="题型">
            <el-radio-group
              v-model="questionsNew.questionType"
              @change="change"
            >
              <el-radio :label="1">单选</el-radio>
              <el-radio :label="2">多选</el-radio>
              <el-radio :label="3">简答</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="难度">
            <el-radio-group v-model="questionsNew.difficulty">
              <el-row>
                <el-radio :label="1">简单</el-radio>
                <el-radio :label="2">一般</el-radio>
                <el-radio :label="3">困难</el-radio>
              </el-row>
            </el-radio-group>
          </el-form-item>
          <!-- 富文本 -->
          <el-form-item label="题干" prop="question">
            <quill-editor
              v-model="questionsNew.question"
              class="quillWidth"
              @change="quillText()"
            ></quill-editor>
          </el-form-item>
          <!-- 选项 -->
          <el-form-item label="选项" prop="name" v-if="ischangeshow">
            <!-- 单选 -->
            <div
              class="option_item"
              v-for="(item, index) in questionsNew.options"
              :key="index"
            >
              <el-radio
                v-model="isRight"
                :label="item.code"
                v-if="isBtnShow"
                style="padding: 0 8px 0 0"
                >{{ item.code + '：' }}</el-radio
              >
              <el-checkbox
                v-model="checkList"
                :label="item.code"
                v-if="isccheckshow"
                style="padding: 0 8px 0 0"
                >{{ item.code + '：' }}</el-checkbox
              >

              <template>
                <el-input
                  v-model="item.title"
                  style="padding: 0 8px 0 0"
                  clearable
                ></el-input>
              </template>
              <el-upload
                class="avatar-uploader"
                action="https://jsonplaceholder.typicode.com/posts/"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img
                  v-if="imageUrl"
                  :src="imageUrl"
                  class="avatar"
                  style="margin-bottom: 5px"
                />
                <span v-else class="span-text" style="text-align: center">
                  发布文件
                  <i class="el-icon-circle-close i-posi"></i>
                </span>
              </el-upload>
            </div>

            <el-button type="danger" :disabled="isBtnShow" @click="addlist"
              >+增加选项与答案</el-button
            >
          </el-form-item>

          <el-form-item label="解析视频">
            <el-input
              class="textWidth"
              v-model="questionsNew.videoURL"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="答案解析" prop="answer">
            <quill-editor
              v-model="questionsNew.answer"
              class="quillWidth"
              @change="answer()"
            ></quill-editor>
          </el-form-item>
          <el-form-item label="题目备注">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="questionsNew.remarks"
              class="textWidth"
              clearable
            >
            </el-input>
          </el-form-item>

          <el-form-item label="试题标签">
            <el-select
              v-model="questionsNew.tags"
              placeholder="请选择试题标签"
              class="textWidth"
              multiple
            >
              <el-option
                v-for="(item, index) in gettagslist"
                :value="item.tagName"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="sumbit"
              >确认提交</el-button
            ></el-form-item
          >
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import { provinces, citys } from '@/api/hmmm/citys'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import {
  getSubjects,
  getdirectorys,
  getcompanys,
  gettags,
  postquestions,
  textApp,
  updatequestions
} from '@/api/hmmm/questions'
import { direction } from '@/api/hmmm/constants'
export default {
  name: 'Que',
  components: {
    quillEditor
  },
  data() {
    return {
      radio: '1',
      // 上传图片
      imageUrl: '',
      // :model 数据绑定
      questionsNew: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        city: '', // 地区
        province: '', // 城市
        topic: '', //
        questions: '', // 试题
        question: '', // 副文本
        questionType: 1,
        difficulty: 1,
        videoURL: '',
        tags: '', // 试题标签
        answer: '', // 答案解析
        remarks: '', // 题目备注
        text: '', // 选项文本
        options: [
          {
            code: 'A',
            title: '',
            isright: false,
            img: ''
          },
          {
            code: 'B',
            title: '',
            isright: false,
            img: ''
          },
          {
            code: 'C',
            title: '',
            isright: false,
            img: ''
          },
          {
            code: 'D',
            title: '',
            isright: false,
            img: ''
          }
        ]
      },

      // 校验规则
      questionsNewRules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择城市', trigger: 'change' }
        ],
        direction: [{ required: true, message: '请选择', trigger: 'change' }],
        question: [{ required: true, message: '请输入题干' }],
        answer: [{ required: true, message: '请输入答案' }]
      },
      // radio 默认选项
      direction: direction,
      isRight: null,
      // 城市 县 数
      provinces: [],
      citys: [],
      Subjectslist: [],
      directoryslist: [],
      companyslist: [],
      isBtnShow: true,
      ischangeshow: true,
      gettagslist: [],
      directionlist: [],
      checkList: [1],
      isccheckshow: false,
      option: 69
    }
  },
  mounted() {
    this.loadlist()
  },
  watch: {
    isRight: function(val) {
      this.questionsNew.options.forEach(item => {
        item.isRight = val === item.code
      })
    }
  },
  methods: {
    addlist() {
      const option = String.fromCharCode(this.option)
      this.questionsNew.options.push({
        code: option,
        title: '',
        isright: false,
        img: ''
      })
      this.option++
    },
    quillText() {
      this.$refs.questionsNewRuleForm.validateField('question')
    },
    answer() {
      this.$refs.questionsNewRuleForm.validateField('answer')
    },
    async sumbit() {
      if (this.$route.query.id) {
        this.questionsNew.tags = this.questionsNew.tags.toString()
        this.questionsNew.questionType = this.questionsNew.questionType.toString()
        this.questionsNew.difficulty = this.questionsNew.difficulty.toString()
        await updatequestions(this.questionsNew)
        this.$message.success('修改成功')
        this.$router.push('/questions/list')
      } else {
        await this.$refs.questionsNewRuleForm.validate(valid => {
          try {
            if (!valid) {
              return this.$message.error('请填写必填的表单项')
            }
            this.questionsNew.tags = this.questionsNew.tags.toString()
            this.questionsNew.questionType = this.questionsNew.questionType.toString()
            this.questionsNew.difficulty = this.questionsNew.difficulty.toString()
            postquestions(this.questionsNew)
            this.$router.push('/questions/list')
            this.$message.success('添加成功')
          } catch (error) {
            // console.log(error)
            this.$message('添加失败')
          }
        })
      }
    },
    citychange(val) {
      this.citys = citys(val)
    },
    async textAtt() {
      try {
        console.log(this.$route.query.id)
        const id = this.$route.query.id
        const { data } = await textApp({ id: id })
        data.questionType = Number(data.questionType)
        data.difficulty = Number(data.difficulty)
        if (data.questionType === 1) {
          data.options.forEach(item => {
            if (item.isRight === 1) {
              this.isRight = item.code
            }
          })
        } else if (data.questionType === 2) {
          const arr = []
          data.options.forEach(item => {
            arr.push(item.code)
          })
          this.isRightArry = arr
        }

        data.tags = data.tags.split(',')
        this.questionsNew = data
        // console.log(this.questionsNew)
      } catch (error) {
        this.$message.error('获取信息失败')
      }
    },
    async changeItem() {
      // 获取目录
      const data = await getdirectorys()
      this.directoryslist = data.data.items
      // 获取标签
      const get = await gettags()
      this.gettagslist = get.data.items
    },
    async loadlist() {
      this.provinces = provinces()
      // 获取学科
      const res = await getSubjects()
      this.Subjectslist = res.data
      // console.log(this.Subjectslist)

      // 获取企业
      const list = await getcompanys()
      this.companyslist = list.data.items

      // 测试回显
      if (this.$route.query.id) {
        this.textAtt()
      }
    },
    change(val) {
      if (val === 1) {
        this.isBtnShow = true
        this.ischangeshow = true
        this.isccheckshow = false
      }
      if (val === 2) {
        this.isBtnShow = false
        this.ischangeshow = true
        this.isccheckshow = true
      }
      if (val === 3) {
        this.ischangeshow = false
      }
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  .el-radio-group {
    width: 100%;
    .el-radio {
      margin-right: 20px;
    }
  }

  .span-text {
    text-align: center;
  }
  .option {
    margin-top: 20px;
  }
  .quillWidth {
    margin-bottom: 22px;
  }
  .textWidth {
    width: 400px !important;
  }
  .el-radio {
    margin-right: 0;
  }
  .option_item {
    .el-input {
      width: 240px;
    }
    .i-posi {
      position: absolute;
      right: -6px;
      top: -7px;
    }
    .avatar-uploader {
      display: inline-block;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      width: 100px;
      height: 60px;
      line-height: 60px;
      margin-left: 5px;
      .span-text {
        text-align: center;
      }
    }
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  text-align: center;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.option_item {
  .avatar-uploader {
    text-align: center;
    margin-bottom: 10px;
  }
}
</style>
